<template>
    <div class="tabs">
        <el-tag size="small" :key="tag.name" v-for="tag in tags"
            :closable="tag.name !== 'home'" :disable-transitions="false"
            @close="handleClose(tag)" @click="changeMenu(tag)"
            :effect="$route.name === tag.name? 'dark' : 'plain'">
            {{tag.label}}
        </el-tag>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'

export default {
  computed: {
    ...mapState({
      tags: state => state.tab.tabList,
      current: state => state.tab.currentMenu
    })
  },
  data () {
    return {

    }
  },
  methods: {
    ...mapMutations({
      close: 'closeTab'
    }),
    // 关闭后，跳转到次
    handleClose (tag) {
      this.close(tag)
      // 删除tab后更新tablist到sessionStorage
      window.sessionStorage.setItem('tabList', JSON.stringify(this.$store.state.tab.tabList))
      if (tag.name === this.current.name) {
        this.changeMenu(this.tags[this.tags.length - 1])
      }
    },
    changeMenu (item) {
      this.$router.push({ name: item.name }) // 根据名字跳转
      this.$store.commit('selectMenu', item)
    }
  },
  created () {
    if (JSON.parse(window.sessionStorage.getItem('tabList'))) {
      console.log(JSON.parse(window.sessionStorage.getItem('tabList')))
      this.$store.state.tab.tabList = JSON.parse(window.sessionStorage.getItem('tabList'))
    }

    if (JSON.parse(window.sessionStorage.getItem('currentMenu'))) {
      this.$store.state.tab.currentMenu = JSON.parse(window.sessionStorage.getItem('currentMenu'))
    }
  }
}
</script>

<style lang="scss" scoped>
.tabs {
  z-index: 9;
  padding: 5px 15px 5px 15px;
  box-shadow:  0px 1px 0px 0px rgba(0, 0, 0, .12);
    .el-tag {
        margin-right: 5px;
        cursor: pointer;
    }
}
</style>
